package de.slothsoft.commons.swing.window;

import java.awt.Window;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.prefs.Preferences;

import de.slothsoft.commons.Option;

public class PreferencesOptionDialog extends OptionDialog {

	private static final long serialVersionUID = 1L;

	private Preferences preferences;

	public PreferencesOptionDialog(Window parent, String title,
			List<Option> options, Preferences preferences) {
		super(parent, title, options, createValueMap(options, preferences));
		this.preferences = preferences;
	}

	public static Map<String, Object> createValueMap(List<Option> theOptions,
			Preferences pref) {
		Map<String, Object> valueMap = new HashMap<String, Object>();

		for (Option option : theOptions) {
			String key = option.getKey();
			Object def = option.getDefaultValue();
			Object value = null;
			switch (option.getValueType()) {
			case BOOLEAN:
				value = pref.getBoolean(key, (Boolean) def);
				break;
			case STRING:
			case MULTI_LINE_STRING:
				value = pref.get(key, (String) def);
				break;
			case INTEGER:
				value = pref.getInt(key, (Integer) def);
				break;
			}
			valueMap.put(key, value);
		}

		return valueMap;
	}

	@Override
	protected void performOkAction() {
		super.performOkAction();

		Map<String, Object> map = getResultingValueMap();
		for (Option option : getOptions()) {
			String key = option.getKey();
			Object value = map.get(key);

			if (value != null) {
				switch (option.getValueType()) {
				case BOOLEAN:
					this.preferences.putBoolean(key,
							((Boolean) value).booleanValue());
					break;
				case STRING:
				case MULTI_LINE_STRING:
					this.preferences.put(key, (String) value);
					break;
				case INTEGER:
					this.preferences.putInt(key, ((Integer) value).intValue());
					break;
				}
			} else {
				this.preferences.remove(key);
			}
		}
	}
}
